package com.example.demo.mvvm.ui.vm.fragment;

import android.content.Intent;
import android.widget.Toast;

import com.example.demo.mvvm.BR;
import com.example.demo.mvvm.R;
import com.example.demo.mvvm.bean.ArticleBean;
import com.example.demo.mvvm.bean.KnowBean;
import com.example.demo.mvvm.bean.ListDto;
import com.example.demo.mvvm.net.BaseObserver;
import com.example.demo.mvvm.net.NetRequest;
import com.example.demo.mvvm.ui.activity.ChildrenActivity;
import com.example.demo.mvvm.ui.activity.WebActivity;
import com.example.demo.mvvm.ui.base.BaseRecyclerViewVM;
import com.example.demo.mvvm.utils.ActivityUtils;
import com.example.demo.mvvm.utils.OnItemClickListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * Created by littlehu on 2018/5/21.
 */

public class ChildrenFragmentVm extends BaseRecyclerViewVM<ArticleBean>{
    private int pageNum = 0;
    private String childrenId;

    public final ItemBinding<ArticleBean> itemBinding = ItemBinding.<ArticleBean>of(BR.item, R.layout.item_home_article).bindExtra(BR.listener, new OnItemClickListener<ArticleBean>() {
        @Override
        public void onItemClick(int viewId , ArticleBean data) {
            switch (viewId){
                case R.id.root:
                    ActivityUtils.push(WebActivity.class , new Intent().putExtra("activityUrl" ,data.getLink() ));
                    break;
                case R.id.chapter_tv:
                    Toast.makeText( ActivityUtils.peek() , data.getChapterName(), Toast.LENGTH_SHORT).show();
            }
        }
    });

    public ChildrenFragmentVm(String childrenId){
        this.childrenId = childrenId;
        listener.set(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                request_data(refreshlayout);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 0;
                request_data(refreshlayout);
            }
        });
    }


    private void request_data(RefreshLayout refreshLayout){
        NetRequest.getChildrenArticle(pageNum, childrenId, new BaseObserver<ListDto<ArticleBean>>(ActivityUtils.peek() , refreshLayout , true) {
            @Override
            public void onSuccess(ListDto<ArticleBean> articleBeanListDto, RefreshLayout refreshLayout) {
                if(pageNum == 0) {
                    items.clear();
                }
                if(articleBeanListDto.getDatas()!=null && articleBeanListDto.getDatas().size() != 0){
                    pageNum = pageNum + 1;
                }
                items.addAll(articleBeanListDto.getDatas());
            }

            @Override
            public void onFailure(int code, String message, RefreshLayout refreshLayout) {

            }
        });
    }


}
